﻿using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.UI;
using CoreShop.Services;
using FastMember;
using Loading;
using MySqlX.XDevAPI.Relational;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using Org.BouncyCastle.Ocsp;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using WebKit;
using static NPOI.HSSF.Util.HSSFColor;
using static System.Windows.Forms.AxHost;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TreeView;

namespace CoreShop.App
{
    public partial class FrmUserEdit : UIForm
    {
        public bool returnValue;
        OpaqueCommand cmd = new OpaqueCommand();
        public corecmsuser member = new corecmsuser();
        public List<VipLevelMode> levelList = null;
        public FrmUserEdit(corecmsuser _member)
        {
            InitializeComponent();
            member = _member;
            cardNo.TextBox.GotFocus += cardNo_GotFocus;
            mobile.TextBox.GotFocus += mobile_GotFocus;     
            mobile.Focus();
            mobile.SelectAll();
        }

        private void cardNo_GotFocus(object sender, System.EventArgs e)
        {
            numKeybord.SetTextBox((UIEdit)sender, UITextBox.UIEditType.String, 0);
        }

        private void mobile_GotFocus(object sender, System.EventArgs e)
        {
            numKeybord.SetTextBox((UIEdit)sender, UITextBox.UIEditType.String, 0);
        }

        private void FrmEditInputs_Load(object sender, EventArgs e)
        {            
            

        }
        private void BindComboBoxData()
        {
            try
            {
                //cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                #region 加载性别信息
                this.sex.Items.Clear();
                var memberSex = EnumHelper.EnumToList<GlobalEnumVars.Sex>();
                sex.DataSource = memberSex;
                sex.DisplayMember = "description";
                sex.ValueMember = "value";
                if (memberSex.Count > 0) this.sex.SelectedIndex = 0;
                #endregion

                #region 加载推荐人信息
                this.parentId.Items.Clear();
                //List<corecmsuser> parentGrid = new corecmsuserServices().SelectByCorpId(GlobalConstVars.sysUser.corpId, GlobalConstVars.sysUser.storeId);
                List<corecmsuser> parentGrid = new corecmsuserServices().QueryAsync(0);
                this.parentId.DataSource = parentGrid;
                this.parentId.DisplayMember = "userName";
                this.parentId.ValueMember = "id";
                if (parentGrid.Count > 0) this.parentId.SelectedIndex = 0;
                #endregion

                LoadVipLevel();
            }
            catch (Exception)
            {
                throw;
            }
            finally {
                //cmd.HideOpaqueLayer();
            }
        }
                
        private async void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                if (!CheckData1()) return;
                string levelId = mbtLevelType.SelectedButtonsValues[0].ToString();
                VipLevelMode vipLevel = levelList.Find(p => p.levelId == levelId);

                if (vipLevel == null)
                {
                    UIMessageBox.Show("会员等级未找到，请选择", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }

                GsPosVip gsVip = member.gsPosVip;

                gsVip.vipTel = mobile.Text.Trim();
                gsVip.vipBirthday = birthday.Text;
                gsVip.vipName = userName.Text;
                gsVip.vipSix = CommFunc.ConvertToInt32(sex.SelectedValue).ToString();
                gsVip.vipLevelId = mbtLevelType.SelectedButtonsValues[0].ToString();
                gsVip.cardNo = cardNo.Text.Trim();
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                ReturnModel returnModel = await MemberApiUtil.UpdateVip(gsVip);

                if (returnModel.Status != ReturnStatus.Success)
                {
                    UIMessageBox.Show($"修改会员信息失败,{returnModel.MessageOrString}");                        
                    return;
                }

                var vipInfo2 = returnModel.MessageOrString.JsonToEntity<VipInfoReturnModel>();
                UIMessageBox.Show("修改成功");
                this.Invoke(new Action(() =>
                {
                    this.DialogResult = DialogResult.Yes;
                }));              
            }
            catch (Exception ex)
            {
                throw;
            }
            finally { cmd.HideOpaqueLayer(); }
        }

        private bool CheckData1()
        {
            if (mobile.Text == null || mobile.Text == "")
            {
                UIMessageBox.Show("请输入电话号码", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }
            if (string.IsNullOrEmpty(userName.Text))
            {
                userName.Text = mobile.Text;
                //UIMessageBox.Show("请输入姓名", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                //return false;
            }
            if (cardNo.Text == null || cardNo.Text == "")
            {
                UIMessageBox.Show("请输入储值卡号", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }            

            if ((levelList == null) || (mbtLevelType.SelectedButtons.Count() == 0))
            {
                UIMessageBox.Show("会员等级未选择，请选择", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }
            return true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void grade_SelectedValueChanged(object sender, EventArgs e)
        {
            //Int64 id = CommFunc.ConvertToInt64(grade.SelectedValue);
            //var gradeModel = gradeGrid.Find(p => p.id == id);
            //if (gradeModel != null) discount.Text = gradeModel.discountValue.ToString() + "%";
        }              

        public async void LoadVipLevel()
        {
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                var rs = await MemberApiUtil.GetVipLevelAsync();
                if (rs.code != 200)
                {
                    ShowSuccessTip("获取等级失败:。" + rs.msg);
                    return;
                }
                List<VipLevelMode> levelListAll = JsonConvert.DeserializeObject<List<VipLevelMode>>(rs.data.ToString());
                levelList = levelListAll.Where(p => p.enable == false).ToList();                
                
                int rows = CommFunc.ConvertToInt32(Math.Ceiling(levelList.Count / 3.0));
                AddLevelItems(levelList, false, new Size(130, 40), 50 * rows, levelList.Count);
            }
            catch(Exception ex)
            {
                ShowSuccessTip("获取等级失败:。" + ex.Message);
            }
            finally { cmd.HideOpaqueLayer(); }
        }


        public void AddLevelItems(List<VipLevelMode> items, bool autoWidth, Size itemSize, int height, int maxSelected = int.MaxValue)
        {
            this.Invoke(new Action(() =>
            {
                string sName = "";
                mbtLevelType.TagString = "等级";
                mbtLevelType.AutoWidth = autoWidth;
                mbtLevelType.MaxSelected = maxSelected;
                mbtLevelType.ItemSize = itemSize;
                mbtLevelType.MaxSelected = 1;
                bool isSelected = false;
                foreach (var item in items)
                {
                    if (item.levelId == member.gsPosVip.vipLevelId) isSelected = true;
                    sName = item.levelName;
                    mbtLevelType.Add(sName, item.levelId.ToLong(), isSelected);
                    isSelected = false;
                }
            }));
        }

        private void numKeybord_OKButtonClick(object sender, string text, int intvalue, double doublevalue)
        {
            btnOk_Click(null, null);
        }

        private void FrmUserEdit_Shown(object sender, EventArgs e)
        {
            BindComboBoxData();
            ControlsDataBinding.DataBind(member, this, DataSourceUpdateMode.OnPropertyChanged);
            try
            {
                if (member.id <= 0)
                {
                    parentId.Text = "";
                    parentId.SelectedValue = 0;
                }
                else
                {
                    corecmsusercategory memberCategory = new corecmsusercategoryServices().GetById(member.userCategoryId);
                    sex.Text = EnumHelper.GetEnumByValue<GlobalEnumVars.Sex>(member.sex.ObjToInt(0));
                    corecmsusergrade memberGrade = new corecmsusergradeServices().GetById(member.grade);
                    if (memberGrade != null)
                    {
                        //grade.Text = memberGrade.title;
                        //discount.Text = memberGrade.discountValue.ToString()+ "%";
                    }
                }
                cardNo.Focus();
                cardNo.SelectAll();
            }
            catch { }
        }
    }
}